<template>
  <div>
    <a-form class="ant-advanced-search-form" :form="form" @submit="handleSubmit">
      <div class="client-header">
        <div class="client-header-title">故障报修</div>
      </div>
      <div class="repair-single-row">
        <a-col span="6" className="service-form">
          <a-form-item label="客户姓名" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['repairman',
                  {
                    initialValue: copyData.repairman || '',
                    rules: [{ required: true, message: '请输入合法的姓名', pattern: /^[\u4e00-\u9fa5]+$/i }]
                    },
                ]"
                      placeholder="请输入客户姓名" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="联系方式" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['phoneNumber',
                  {
                    initialValue: copyData.phoneNumber || '',
                    rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3|4|5|7|8|9][0-9]\d{8}$/}]
                    },
                ]"
                      placeholder="请输入联系方式" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="客户单位" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['companyName',
                  {
                    initialValue: copyData.companyName || '',
                    rules: [{ required: true, pattern: /\S/, message: '请输入客户单位' }]
                    },
                ]"
                      placeholder="请输入客户单位" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="机床编号" class="repair-form">
            <a-input class="deploy-form-single-input" v-decorator="['macNumb',
                  {
                    initialValue: copyData.macNumb || '',
                    rules: [{ required: true, pattern: /^[a-zA-Z0-9_]{1,20}$/, message: '机床编号仅限数字字母和下划线' }]
                    },
                ]"
                     placeholder="请输入机床编号(仅限数字字母和下划线)" autoComplete="off" />
          </a-form-item>
        </a-col>
      </div>
      <div class="repair-single-row">
        <a-col span="6" className="service-form">
          <a-form-item label="机床型号" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['macType',
                  {
                    initialValue: copyData.macType || '',
                    rules: [{ required: true, pattern: /\S/, message: '请输入机床型号' }]
                    },
                ]"
                      placeholder="请输入机床型号" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="系统型号" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['ncSystemType',
                  {
                    initialValue: copyData.ncSystemType || '',
                    rules: [{ required: true, pattern: /\S/, message: '请输入系统型号' }]
                    },
                ]"
                      placeholder="请输入系统型号" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="机床厂家" class="repair-form">
            <a-input  class="deploy-form-single-input" v-decorator="['macFactory',
                  {
                    initialValue: copyData.macFactory || '',
                    rules: [{ required: true, pattern: /\S/, message: '请输入机床厂家' }]
                    },
                ]"
                      placeholder="请输入机床厂家" autoComplete="off" />
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="机床位置" class="repair-form">
            <a-select show-search option-filter-prop="children"
                      v-decorator="['address',
          { initialValue: copyData.address || '北京市',
            rules: [{ required: true, message: '请输入机床位置' }] },
        ]"
                      placeholder="请选择案例类型"
            >
              <a-select-option v-for="provinceItem in provinceData" :key="provinceItem" :value="provinceItem">
                {{provinceItem}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </div>
      <div class="repair-single-row">
        <a-col span="6" className="service-form">
          <a-form-item label="报修机床厂" class="repair-form">
            <a-select show-search option-filter-prop="children"
                      v-decorator="['repairCompany',
          { initialValue: copyData.repairCompany || repairCompany[0].compName,
            rules: [{ required: true, pattern: /\S/, message: '请输入报修机床厂' }] },
        ]"
                      placeholder="请选择报修机床厂"
            >
              <a-select-option v-for="companyItem in repairCompany"
                               :key="companyItem.id" :value="companyItem.compName">
                {{companyItem.compName}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col span="6" className="service-form">
          <a-form-item label="设备购买时间" class="repair-form">
            <a-date-picker  class="deploy-form-single-input"
                            :disabled-date="disabledDate"
                            v-decorator="['purchaseTime',
                  {
                    initialValue: purchaseTime || doHandleDate,
                    rules: [{ required: true, pattern: /\S/, message: '请输入设备购买时间' }]
                    },
                ]"
                            placeholder="请输入设备购买时间" autoComplete="off" />

          </a-form-item>
        </a-col>
      </div>
      <div class="repair-single-row">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="用户地址"
        >
          <a-textarea class="repair-desc"
                      v-decorator="['fullAddress',
          { initialValue: copyData.fullAddress || '',
            rules: [{ required: true, pattern: /\S/, message: '请输入用户地址' }] },
        ]"
                      placeholder="请输入用户地址"  autoComplete="off"
          />
        </a-form-item>
      </div>
      <div class="repair-single-row">
        <a-form-item
          :label-col="formItemLayout.labelCol"
          :wrapper-col="formItemLayout.wrapperCol"
          label="请描述详细情况"
        >
          <a-textarea class="repair-desc"
                      v-decorator="['description',
          { initialValue: copyData.description || '',
            rules: [{ required: true, pattern: /\S/, message: '请输入详细情况' }] },
        ]"
                      placeholder="请输入详细情况"  autoComplete="off"
          />
        </a-form-item>
      </div>
      <div class="repair-single-row">
        <a-form-item class="form-item"
                     :label-col="formItemLayout.labelCol"
                     :wrapper-col="formItemLayout.wrapperCol"
                     label=""
        ><span class="pic-must">✻</span><span class="pic-must-title">请添加图片:</span>
          <upload-image @changeFileList="changeFileList"></upload-image>
        </a-form-item>
      </div>
      <div class="repair-single-row repair-single-submit-row">
        <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
          <a-button type="primary" html-type="submit" :disabled="isDisabled" class="repair-submit">
            提&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;交</a-button>
        </a-form-item>
      </div>
    </a-form>
  </div>
</template>

<script>
  //获取当前时间, 1精确到天, 2精确到分
  function getCurrentDate(format) {
    let now = new Date();
    let year = now.getFullYear(); //得到年份
    let month = now.getMonth();//得到月份
    let date = now.getDate();//得到日期
    let hour = now.getHours();//得到小时
    let minu = now.getMinutes();//得到分钟
    let sec = now.getSeconds();//得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    let time = "";
    //精确到天
    if (format === 1) {
      time = year + "-" + month + "-" + date;
    }
    //精确到分
    else if (format === 2) {
      time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
    }
    return time;
  }
  import UploadImage from './components/Image'
  import api from '@/server/userConfig';
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
  import moment from 'moment';
  import 'moment/locale/zh-cn';
  export default {
    name: "Repair",
    components: {
      UploadImage
    },
    computed: {
      doHandleDate: function () {
        const myDate = new Date();
        const tYear = myDate.getFullYear();
        const tMonth = myDate.getMonth();
        const tDay = myDate.getDate();
        let m = tMonth + 1;
        if (m.toString().length === 1) {
          m = "0" + m;
        }
        return moment(tYear +'-'+ m + '-' + tDay);
      }
    },
    data () {
      return {
        userName: '',
        provinceData: ["北京市","天津市","上海市","重庆市","河北省","山西省","内蒙古","辽宁省","吉林省","黑龙江省","江苏省","浙江省","安徽省",
          "福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","广西","海南省","四川省","贵州省","云南省","西藏","陕西省","甘肃省",
          "青海省","宁夏","新疆","香港","澳门","台湾省", "研究院"],
        formItemLayout: {
          labelCol: { span: 2 },
          wrapperCol: { span: 14 },
        },
        repairCompany: [{compId: -1, compName: '华中数控'}],
        isDisabled: false,
        picturesId: '',
        copyData: {},
        purchaseTime: ''
      }
    },
    beforeCreate () {
      this.form = this.$form.createForm(this, { name: 'validate_other' });
    },
    methods: {
      disabledDate (current) {
        // Can not select days before today and today
        return current && current > moment().endOf('day');
      },
      // 点击提交;
      handleSubmit (e) {
        e.preventDefault();
        this.form.validateFields( async (err, values) => {
          if (!err) {
            this.isDisabled = true;
            let repairData = {};
            const newTime = values['purchaseTime'].format('YYYY-MM-DD');
            repairData.uploadTime = getCurrentDate(2);
            repairData.description = values.description;
            repairData.fullAddress = values.fullAddress;
            repairData.repairman = values.repairman;
            repairData.phoneNumber = values.phoneNumber;
            repairData.companyName = values.companyName;
            repairData.macNumb = values.macNumb;
            repairData.macType = values.macType;
            repairData.ncSystemType = values.ncSystemType;
            repairData.macFactory = values.macFactory;
            repairData.address = values.address;  // 机床位置;
            repairData.repairCompany = values.repairCompany;   // 报修机床厂;
            repairData.purchaseTime = newTime;   // 设备购买时间;
            repairData.picturesId = this.picturesId;
            repairData.username = this.userName;
            repairData.state = 1;
            console.log(repairData);
            // if (!repairData.picturesId) {
            //   this.$message.info('请至少添加一张图片');
            //   return;
            // }
            const jsonRepairData = JSON.stringify(repairData);
            api.reqHandleRepair(jsonRepairData).then((res) => {
              if (res.MsgCode === 0) {
                this.$Modal.success({
                  title: '',
                  content: '报修成功!',
                  okText: '确定'
                });
              } else {
                this.$message.error('报修失败...');
              }
            })
          }
        })
      },
      changeFileList (fileList) {
        let picturesId = '';
        let pictureIdArr = [];
        if (fileList.length === 0) {
          picturesId = '';
        } else {
          for (let i = 0; i < fileList.length; i++) {
            pictureIdArr.push(fileList[i].id);
            picturesId = pictureIdArr.join(',');
          }
        }
        this.picturesId = picturesId;
      },
      getLocalStorageData () {
        const phone = localStorage.getItem('phone');
        this.userName = phone;
        if (!phone) {
          this.$router.push('/');
        }
      },
      // 省份选择Select;
      handleSelectChange (value) {
        console.log(`selected ${value}`);
      },
      // 初始化获取报修机床厂;
      async initRepairCompany () {
        try {
          const res = await api.reqGetRepairCompany({userName: this.userName});
          if (res.MsgCode !== 0) {
            this.$message.error('获取报修机床厂失败...');
            return;
          }
          this.repairCompany = res.Data;
        } catch (e) { console.log(e); }
      },
      // 复制工单的数据;
      initBillCopy (id) {
        if (id == 0) {
          this.copyData = {};
        } else if (id == 1) {
          const copyData = JSON.parse(localStorage.getItem("copyData"));
          console.log(copyData);
          this.copyData = copyData;
          this.purchaseTime = moment(copyData.purchaseTime);
        }
      },
    },
    mounted () {
      const { id } = this.$route.params;
      this.getLocalStorageData();
      this.initRepairCompany();
      this.initBillCopy(id);
    }
  }
</script>

<style scoped="scoped">
  @import "./components/style.css";
</style>
